<?php
/**
 * User: YL
 * Date: 2019/09/12
 */

namespace restful\utils;

use Illuminate\Http\Request;
use Illuminate\Routing\Route;

class Dispatch
{
    /**
     * @var static
     */
    protected static $instance;

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var Route
     */
    protected $route;

    private function __construct(Request $request)
    {
        $this->request = $request;
        $this->route = app('router')->getRoutes()->match($request);
    }

    /**
     * getInstance
     * @param Request $request
     * @return static
     */
    public static function getInstance(Request $request)
    {
        if (is_null(static::$instance)) {
            static::$instance = new static($request);
        }

        return static::$instance;
    }

    /**
     * 运行
     * @param string $controller
     * @param string $method
     * @param null $result
     * @param mixed ...$params
     * @return mixed|null
     */
    public static function run(string $controller, string $method, $result = null, ...$params)
    {
        if (method_exists($controller, $method)) {
            return call_user_func([$controller, $method], ...$params);
        }

        return $result;
    }

    /**
     * 获取请求对象
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * 获取当前路由
     * @return Route
     */
    public function getRoute()
    {
        return $this->route;
    }

    /**
     * 获取控制器名称
     * @return string
     */
    public function getController()
    {
        $arr = explode('@', $this->route->getActionName());
        return $arr[0] ?? '';
    }

    /**
     * 获取方法名称
     * @return string
     */
    public function getMethod()
    {
        return $this->route->getActionMethod();
    }

    /**
     * 获取模块名称
     * @return string
     */
    public function getModule()
    {
        $arr = explode('\\', $this->route->getAction('namespace'));
        return $arr[2] ?? '';
    }
}
